package com.rjs.nio.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

	public static void main(String[] args) throws IOException {
//		generateFile();
//		readFile();
		readNIO();
		writeNIO();
	}
	
	private static void writeNIO() throws IOException {
		RandomAccessFile accessFile = new RandomAccessFile("src/test/resources/nio-buffer.txt", "rw");
		FileChannel channel = accessFile.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(1024);
		buf.put("hello world".getBytes());
		//写入数据后position会指向下一个可写位置，需要用flip调整为读模式，否则直接调用channel的write方法无法写入数据
		buf.flip();
		//无法保证write方法一次性写完
		while(buf.hasRemaining()) {
			channel.write(buf);
		}
		accessFile.close();
	}
	
	private static void readNIO() throws IOException {
		RandomAccessFile accessFile = new RandomAccessFile("src/test/resources/nio-data.txt", "rw");
		FileChannel channel = accessFile.getChannel();
		
		ByteBuffer buf = ByteBuffer.allocate(1024);
		int len = -1;
		while((len = channel.read(buf)) != -1) {
			buf.flip();
			System.out.println(buf.getFloat());
			System.out.println(readUTF(buf));
			System.out.println(readUTF(buf));
			System.out.println(buf.getInt());
//			while(buf.hasRemaining()) {
//				System.out.print((char)buf.get());
//			}
			buf.clear();
		}
		accessFile.close();
	}
	
	private static String readUTF(ByteBuffer buffer) {
		int strLength = buffer.getShort();
		byte[] buf = new byte[strLength];
		buffer.get(buf);
		return new String(buf);
	}
	
	@SuppressWarnings("unused")
	private static void generateFile() throws IOException {
		RandomAccessFile accessFile = new RandomAccessFile("src/test/resources/nio-data.txt", "rw");
		accessFile.writeFloat(2.35f);
		//writeUTF会先写一个unsigned short表示字符串的长度（最大支持65535），再写入字符串
		accessFile.writeUTF("hello world111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
		accessFile.writeUTF("你好呀");
		accessFile.writeInt(5);
		accessFile.close();
	}
	
	@SuppressWarnings("unused")
	private static void readFile() throws IOException {
		RandomAccessFile accessFile = new RandomAccessFile("src/test/resources/nio-data.txt", "r");
		accessFile.seek(4);
		int readShort = accessFile.readUnsignedShort();
		System.out.println(readShort);
		byte[] b = new byte[readShort];
		accessFile.read(b);
		System.out.println(new String(b));
		//readUTF会先读一个unsigned short表是字符串的长度，再读取对应长度的字符串
		System.out.println(accessFile.readUTF());
		System.out.println(1 << 16);
		accessFile.close();
	}
}
